package com.ylkj.wx.facade.impl;

import java.io.IOException;
import java.security.NoSuchAlgorithmException;
import java.util.Date;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.sword.wechat4j.token.TokenProxy;

import com.ylkj.wx.constant.WeiXBaseConstant;
import com.ylkj.wx.entitis.AccessTokenEntity;
import com.ylkj.wx.exception.WeichatException;
import com.ylkj.wx.facade.WXInfoFacade;
import com.ylkj.wx.utils.DateUtil;
import com.ylkj.wx.utils.ShaUtil;
import com.ylkj.wx.utils.WeixCommonUtil;

@Service
public class WXInfoFacadeImpl implements WXInfoFacade {
    private static final Logger LOGGER = LoggerFactory.getLogger(WXInfoFacadeImpl.class);
    
    private static final long EXPIRES_TIME = 1*30*60*1000;

	/* (non-Javadoc)
	 * @see com.xikang.ch.cloudweix.facade.WXInfoFacade#setAccessTokenToRedis()
	 */
	@Override
	public void setWXInfoToRedis() {
		// 保存accessToken
		//String accessToken = setAccessToken();
		//setJsapiTicket(accessToken);
	}
	
	/*private String setAccessToken() {
		String accessToken = "";
		String nextTime = "";
		try {
			// 从redis中获得Access_Token，和AccessExpires
			AccessTokenEntity accessTokenEntity = CacheHelper.getObject(WeiXBaseConstant.ACCESS_TOKEN_KEY, AccessTokenEntity.class);
			boolean needSetToRedis = false;
			// redis中没有该对象
			if (accessTokenEntity == null) {
				accessTokenEntity = new AccessTokenEntity();
				needSetToRedis = true;
			}else{
				String expires = accessTokenEntity.getAccessExpires();
				Date expiresDate = DateUtil.strToDate(DateUtil.yyyy_MM_dd_HH_mm_ss, expires);
				long expiresTime = expiresDate.getTime();
				long nowTime = new Date().getTime();
				if(nowTime - expiresTime >= EXPIRES_TIME){
					needSetToRedis = true;
				} else {
					accessToken = accessTokenEntity.getAccessToken();
				}
			}
			
			if (needSetToRedis) {
				// 获得accesstoke与更新时间
				accessToken = WeixCommonUtil.getAccessToken();
				nextTime = setInfoToRedis(accessToken, accessTokenEntity, WeiXBaseConstant.ACCESS_TOKEN_KEY);
				LOGGER.info("accessToken is "+ accessToken);
				LOGGER.info("accessToken accessExpires is "+ nextTime);
			} else {
				LOGGER.info("accessToken is not change.accessToken is " + accessToken );
			}
			
		} catch (Exception ex) {
			LOGGER.error("accessToken读写失败！", ex);
		}
		return accessToken;
	}*/
	
	/*private String setJsapiTicket(String accessToken){
		String japiTicket = "";
		if(StringUtils.isEmpty(accessToken)){
			LOGGER.warn("accessToken is empty.");
			return japiTicket;
		}
		String nextTime = "";
		try {
			AccessTokenEntity jsapiTicketEntity = CacheHelper.getObject(WeiXBaseConstant.JSAPI_TICKET_KEY, AccessTokenEntity.class);
			// 从redis中获得Access_Token，和AccessExpiresACCESS_TOKEN_KEY
			boolean needSetToRedis = false;
			// redis中没有该对象
			if (jsapiTicketEntity == null) {
				jsapiTicketEntity = new AccessTokenEntity();
				needSetToRedis = true;
			}else{
				String expires = jsapiTicketEntity.getAccessExpires();
				if(StringUtils.isNotBlank(expires)){
					Date expiresDate = DateUtil.strToDate(DateUtil.yyyy_MM_dd_HH_mm_ss, expires);
					long expiresTime = expiresDate.getTime();
					long nowTime = new Date().getTime();
					if(nowTime - expiresTime >= EXPIRES_TIME){
						needSetToRedis = true;
					} else {
						japiTicket = jsapiTicketEntity.getAccessToken();
					}
				} else {
					needSetToRedis = true;
				}
				
			}
			if (needSetToRedis) {
				// 获得accesstoke与更新时间
				japiTicket = WeixCommonUtil.getJsapiTicket(accessToken);
				//nextTime = setInfoToRedis(japiTicket, jsapiTicketEntity, WeiXBaseConstant.JSAPI_TICKET_KEY);
				
				LOGGER.info("japiTicket is "+ japiTicket);
				LOGGER.info("japiTicket accessExpires is "+ nextTime);
			} else {
				LOGGER.info("japiTicket is not change.japiTicket is "+ japiTicket);
			}
		} catch (Exception ex) {
			LOGGER.error("accessToken读写失败！", ex);
		}
		
		return japiTicket;
	}*/

	/**  
	 * <p>保存到redis中</p>
	 * @param accessToken
	 * @param accessTokenEntity
	 * @return
	 * @throws ComponentBussException String
	 * @since   1.0.0
	 */ 
/*	private String setInfoToRedis(String accessToken,
			AccessTokenEntity accessTokenEntity, String redisKey) throws ComponentBussException {
		Date accessExpires;
		String nextTime;
		Date now = new Date();
		accessExpires = new Date(now.getTime());
		nextTime = DateUtil.dateToStr(DateUtil.yyyy_MM_dd_HH_mm_ss, accessExpires);
		accessTokenEntity.setAccessToken(accessToken);
		accessTokenEntity.setAccessExpires(nextTime);
		// 更新到redis中
		CacheHelper.add(redisKey, accessTokenEntity);
		return nextTime;
	}*/
	
	/* (non-Javadoc)
	 * @see com.xikang.ch.cloudweix.facade.WXInfoFacade#getAccessToken()
	 */
	@Override
	public String getAccessToken() {
		String accessToken = TokenProxy.accessToken();
	/*	try {
			// 从redis中获得Access_Token，和AccessExpires
			AccessTokenEntity jsapiTicketEntity = CacheHelper.getObject(WeiXBaseConstant.ACCESS_TOKEN_KEY, AccessTokenEntity.class);
			if (jsapiTicketEntity != null) {
				accessToken = jsapiTicketEntity.getAccessToken();
			}
		} catch (Exception e) {
			LOGGER.error("accessToken读取失败！", e);
		}*/
		LOGGER.info("accessToken is ===" + accessToken);
		return accessToken;
	}

	/* (non-Javadoc)
	 * @see com.xikang.ch.cloudweix.facade.WXInfoFacade#getJsapiTicket()
	 * 获取tocken
	 */
	@Override
	public String getJsapiTicket() throws IOException, WeichatException {
		String jsapiTicket = "";
		String accessToken =getAccessToken();
		jsapiTicket = WeixCommonUtil.getJsapiTicket(accessToken);
		/*try {
			// 从redis中获得Access_Token，和AccessExpires
			AccessTokenEntity jsapiTicketEntity = CacheHelper.getObject(WeiXBaseConstant.JSAPI_TICKET_KEY, AccessTokenEntity.class);
			if (jsapiTicketEntity != null) {
				jsapiTicket = jsapiTicketEntity.getAccessToken();
			}
		} catch (Exception e) {
			LOGGER.error("jsapiTicket读取失败！", e);
		}*/
		LOGGER.info("jsapiTicket is ===" + jsapiTicket);
		return jsapiTicket;
	}

	/* (non-Javadoc)
	 * @see com.xikang.ch.cloudweix.facade.WXInfoFacade#getSignature()
	 * 1、使用APPID和APPSecret获取access_token；
2、使用access_token获取jsapi_ticket ；
3、用时间戳、随机数、jsapi_ticket和要访问的url按照签名算法拼接字符串；
4、对第三步的字符串进行SHA1加密，得到签名。
	 */
	@Override
	public String getSignature(long timestamp, String nonce, String jsurl) throws NoSuchAlgorithmException, IOException, WeichatException {
		String jsapiTicket = getJsapiTicket();
		LOGGER.info(jsapiTicket +" === "+ timestamp+" === " + nonce+" === " + jsurl);
		String signature = ShaUtil.getJsapiTicket(jsapiTicket, timestamp, nonce, jsurl);
		LOGGER.info("signature is ===" + signature);
		return signature;
	}
    
}
